package parsers.teacher;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import dao.Linker;

import parsers.CommonMethods;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.Source;

import model.Time;
import model.Warning;
import model.teacher.Day;
import model.teacher.Subject;
import model.teacher.Teacher;

public class TeacherParser
{	
	private Teacher teacher;
	
	public TeacherParser(Teacher teacher) 
	{
		this.teacher = teacher;
	}
	
	public Teacher parse(boolean linkWithParent) throws IOException
	{
		Source source = new Source(new URL(teacher.getLink()));
		Teacher teacher = null;
		
		if(linkWithParent)
		{
			teacher = this.teacher;
		}
		else
		{
			String link = this.teacher.getLink();
			String id = this.teacher.getId();
			teacher = new Teacher(this.teacher.getName(), this.teacher.getUnit());
			teacher.setId(id);
			teacher.setLink(CommonMethods.parseLink(link));
		}
		
		Linker.teacherList.add(teacher);
		
		List<Element> elements = source.getAllElements(HTMLElementName.TR);
		
		Day day = null;
		
		for (Element element : elements)
		{
			List<Element> e = element.getAllElements("b");
			for (Element element2 : e)
			{
				if(CommonMethods.checkDay(element2.getContent().toString()))
				{
					day = teacher.createDay(element2.getContent().toString());
				}
			}
			
			if(day != null)
			{
				e = element.getAllElements("tr");
				for (Element element2 : e)
				{
					Segment s = element2.getContent();
					List<Element> el = s.getAllElements("td");
					
					if(el.size() > 1)
					{
						Warning warning = new Warning(CommonMethods.parseElement(el.get(6)));
						Linker.warningRAWList.add(warning);
						Subject subject = day.createSubject(new Time(CommonMethods.checkSpace(el.get(0).getContent().toString()), CommonMethods.checkSpace(el.get(1).getContent().toString())), el.get(2).getContent().toString(), el.get(3).getContent().toString(), warning);
						
						CommonMethods.parseGroups(el.get(4), subject);
						CommonMethods.parseLectureRooms(el.get(5), subject);
					}
				}
			}
		}
		
		return teacher;
	}
	
	/*public static void main(String[] args) throws MalformedURLException, IOException
	{
		Teacher t = new Teacher("mgr inż. Marcel Luzar", "Instytut Sterowania i Systemów Informatycznych");
		t.setLink("file:/D:/test6.html");
		
		TeacherParser tp = new TeacherParser(t);
		Teacher tNew = tp.parse(false);
		System.out.println(tNew);
	}*/
}
